//
//  LeveyPopListView.m
//  LeveyPopListViewDemo
//
//  Created by Levey on 2/21/12.
//  Copyright (c) 2012 Levey. All rights reserved.
//

#define SECTIONHEIGHT 25
#define ROWHEIGHT 40
#define BUTTONCANNELTAG  100
#define BUTTONOKTAG  101
#import "EditPopListView.h"
#import "Utility.h"
#import "Config.h"
#import "EditPopListViewCell.h"



@interface EditPopListView (private)
- (void)fadeIn;
@end

@implementation EditPopListView
@synthesize delegate;
#pragma mark - initialization & cleaning up
- (id)initWithOptions:(NSArray *)aOptions
{
    CGRect rect = [[UIScreen mainScreen] bounds];
    if (self = [super initWithFrame:rect])
    {
        self.backgroundColor = [UIColor clearColor];
        int i=0;
        for (NSDictionary *dict in aOptions) {
            i+=[[dict objectForKey:@"list"] count];
        }
        if (i>6) {
            i=6;
        }
        float tableheight=26+30;
        tableheight+=SECTIONHEIGHT*aOptions.count+ROWHEIGHT*i;
        
        UIImageView *tablebakgroundimageView=[[UIImageView alloc] initWithFrame:CGRectMake(120, -5, 203, tableheight+27)];
        tablebakgroundimageView.userInteractionEnabled=YES;
        UIImage *image=[Utility imageNamed:@"editpopbg.png"];
        UIEdgeInsets insets=UIEdgeInsetsMake(25, 0, 25, 0);
        if ([[[UIDevice currentDevice] systemVersion] floatValue]<6.0) {
            image=[image resizableImageWithCapInsets:insets];
        }else{
            image=[image resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
        }
        tablebakgroundimageView.image=image;
        [self addSubview:tablebakgroundimageView];
        self.options =[NSMutableArray arrayWithArray:aOptions];
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(8,12,185,tableheight) style:UITableViewStyleGrouped];
        self.tableView.backgroundColor = [UIColor clearColor];
        self.tableView.backgroundView=nil;
        self.tableView.dataSource = self;
        self.tableView.delegate = self;
        //self.tableView.scrollEnabled=NO;
        self.tableView.showsVerticalScrollIndicator=NO;
        self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
       // _tableView.separatorColor=[UIColor redColor];
        [tablebakgroundimageView addSubview:self.tableView];
        
       

    }
    return self;    
}

- (void)dealloc
{
}

#pragma mark - Private Methods
- (void)fadeIn{
    CGRect frame=self.frame;
    frame.origin.y=-frame.size.height+64;
    self.frame=frame;
    [UIView animateWithDuration:0.5
                          delay: 0.0
                        options: UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         CGRect frameEnd=self.frame;
                         frameEnd.origin.y=0;
                         self.frame=frameEnd;
                     }
                     completion:^(BOOL finished){
   
                     }];
}
- (void)fadeOut{
    __weak id weakSelf=self;
    [UIView animateWithDuration:0.3
                          delay: 0.0
                        options: UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         CGRect frame=self.frame;
                         frame.origin.y=-frame.size.height;
                         self.frame=frame;
                     }
                     completion:^(BOOL finished){
                         __strong id strongSelf=weakSelf;
                        [strongSelf removeFromSuperview];
                     }];
}

#pragma mark - Instance Methods
- (void)showInView:(UIView *)aView animated:(BOOL)animated
{
    [aView addSubview:self];
    if (animated) {
        [self fadeIn];
    }
}
//指定有多少个分区(Section)，默认为1
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.options count]+1;
}

#pragma mark - Tableview datasource & delegates
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==2) {
        return 0;
    }
    return [[[self.options  objectAtIndex:section] objectForKey:@"list"] count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section==2) {
        return 30;
    }else{
       return 25;
    }
    
}
//表视图委托
#pragma mark - Tableview datasource & delegates
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
     
    if (section<2) {
        UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 25)];
        UILabel *label=[Utility  detailTextLabel:CGRectMake(15, 4, 200, 17) andFontSize:12.0];
        label.text=[[self.options  objectAtIndex:section] objectForKey:@"title"];
        label.textColor=[UIColor blackColor];
        [view addSubview:label];
        return view;
    }else{
        UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
        [view addSubview:[Utility customButton:self action:@selector(onclickButtonAction:) normalImage:@"editpop_canel_normal.png" lightedImage:@"editpop_canel_hover.png" frame:CGRectMake(6, 0, 85, 30) title:nil tag:BUTTONCANNELTAG]];
        [view  addSubview:[Utility customButton:self action:@selector(onclickButtonAction:) normalImage:@"editpop_ok_normal.png" lightedImage:@"editpop_ok_hover.png" frame:CGRectMake(95, 0, 85, 30) title:nil tag:BUTTONOKTAG]];
        return view;
    }
   
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentity = @"editPopListViewCell";
    
    EditPopListViewCell *cell = (EditPopListViewCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentity];
    if (cell ==  nil) {
        cell = [[EditPopListViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentity];
    }
    NSDictionary *dict=[[[self.options  objectAtIndex:indexPath.section] objectForKey:@"list"] objectAtIndex:indexPath.row];
    cell.content.text=[dict objectForKey:@"content"];
    if ([[dict objectForKey:@"flag"] integerValue]==1) {
        cell.selectButtonImage.image=[Utility imageNamed:@"select_hover.png"];
    }else{
        cell.selectButtonImage.image=[Utility imageNamed:@"select_normal.png"];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        NSMutableArray *newArray=[NSMutableArray array];
        NSMutableDictionary *dictsection0=[NSMutableDictionary dictionaryWithDictionary:[self.options objectAtIndex:indexPath.section]];
        NSArray *array=[dictsection0 objectForKey:@"list"];
        for (int i=0;i<array.count;i++) {
             NSMutableDictionary *newdict=[NSMutableDictionary dictionaryWithDictionary:array[i]];
            if (i==indexPath.row) {
                 newdict[@"flag"]=@"1";
            }else{
                 newdict[@"flag"]=@"0";
            }
            [newArray addObject:newdict];
        }
        [dictsection0 setObject:newArray forKey:@"list"];
        [self.options removeObjectAtIndex:indexPath.section];
        [self.options insertObject:dictsection0 atIndex:indexPath.section];
        [self.tableView reloadData];
    }else if(indexPath.section==1){
        NSMutableDictionary *dictsection=[NSMutableDictionary dictionaryWithDictionary:[self.options objectAtIndex:indexPath.section]];
        NSMutableArray *array=[NSMutableArray arrayWithArray:[dictsection objectForKey:@"list"]];
        NSMutableDictionary *rowdict=[NSMutableDictionary dictionaryWithDictionary:[array objectAtIndex: indexPath.row]];
        if ([[rowdict objectForKey:@"flag"] integerValue]==1) {
            [rowdict setObject:@"0" forKey:@"flag"];

        }else{
            [rowdict setObject:@"1" forKey:@"flag"];

        }
        [array removeObjectAtIndex:indexPath.row];
        [array insertObject:rowdict atIndex:indexPath.row];
        [dictsection setObject:array forKey:@"list"];
        [self.options removeObjectAtIndex:indexPath.section];
        [self.options insertObject:dictsection atIndex:indexPath.section];
        [self.tableView reloadData];
    }
}
#pragma mark - TouchTouchTouch
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    // tell the delegate the cancellation
    if (self.delegate && [self.delegate respondsToSelector:@selector(editPopListViewDidCancel)]) {
        [self.delegate editPopListViewDidCancel];
    }
    
    // dismiss self
    [self fadeOut];
}
-(void) onclickButtonAction:(UIButton*) sender{
    if ([sender tag]==BUTTONCANNELTAG) {//取消
        if (self.delegate && [self.delegate respondsToSelector:@selector(editPopListViewDidCancel)]) {
            [self.delegate editPopListViewDidCancel];
        }
       
    }else if([sender tag]==BUTTONOKTAG){
        if (self.delegate && [self.delegate respondsToSelector:@selector(editPopListViewDidSelected:andTags:)]) {
            NSArray *category=[[NSMutableDictionary dictionaryWithDictionary:[self.options objectAtIndex:0]] objectForKey:@"list"];
            NSUInteger categoryId=0;
            for (NSDictionary *dict in category) {
                if ([[dict objectForKey:@"flag"] integerValue]==1) {
                    categoryId=[[dict objectForKey:@"id"] integerValue];
                }
            }
           
            NSArray *tagArray=[[NSMutableDictionary dictionaryWithDictionary:[self.options objectAtIndex:1]] objectForKey:@"list"];
            NSString *tags=@"";
            for (NSDictionary *dict in tagArray) {
                if ([[dict objectForKey:@"flag"] integerValue]==1) {
                    tags=([tags isEqualToString:@""]?[dict objectForKey:@"id"]:[NSString stringWithFormat:@"%@,%@",tags,[dict objectForKey:@"id"]]);
                }
            }
            [self.delegate  editPopListViewDidSelected:categoryId andTags:tags];
        }
    }
    
}


@end
